<template>
  <div class="detect">
    <a-page-header
      style="border: 0px solid rgb(235, 237, 240)"
      title="YOLOv5 detect"
      sub-title="请选择权重"
    >
      <template #tags>
        <!-- <a-select
          v-model:value="weight"
          :options="options"
          style="width: 120px"
          ref="select"
          @change="changeWeight"
        >
        </a-select> -->
        <a-tag color="blue" @click="changeWeightFolder()">
          {{ weight }}
        </a-tag>
      </template>
    </a-page-header>
    <a-drawer
      width="200"
      title="Select Weight"
      placement="left"
      :closable="true"
      v-model:visible="drawer_visible"
      :get-container="false"
      :wrap-style="{ position: 'absolute' }"
    >
      <a-list item-layout="horizontal" :data-source="options">
        <template #renderItem="{ item, index }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>
                <a @click="changeWeight(item.value)">{{ item.value }}</a>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-drawer>
    <a-row type="flex" justify="space-around">
      <!-- 左侧上传图片 -->
      <a-col :span="11">
        <a-upload-dragger
          list-type="picture-card"
          class="avatar-uploader ant-upload"
          :show-upload-list="false"
          :action="yolov_detect_url"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="" />
          <div v-else>
          <loading-outlined v-if="loading" />
          <p class="ant-upload-drag-icon" v-else>
            <inbox-outlined />
          </p>
          <p class="ant-upload-text">
            点击上传，或拖拽图片至此
          </p>
          <p class="ant-upload-hint">
            <br> 单张图片不大于 2 M，格式仅限 png 或 jpeg
          </p>
          </div>
        </a-upload-dragger>
      </a-col>

      <!-- 右侧输出图片 -->
      <a-col :span="11">
        <a-card hoverable>
            <template v-slot:cover>
            <img v-if="detectedImageUrl" alt="" :src="detectedImageUrl" />
            <a-empty v-else />
            </template>
        </a-card>
      </a-col>
    </a-row> 
  </div>
</template>

<script>
  import { LoadingOutlined, InboxOutlined  } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  export default {
    components: {
      LoadingOutlined, InboxOutlined 
    },
    data() {
      return {
        yolov_detect_url: this.$axios.defaults.baseURL + "/yolov/detect",
        yolov_weights_url: this.$axios.defaults.baseURL + "/yolov/get_weights",
        loading: false, 
        imageUrl: '', 
        detectedImageUrl: '', 
        weight: 'yolov5s.pt',
        options: [
          // {
          //   value: 'yolov5s',
          // }
        ], 
        time_spent: undefined, 
        drawer_visible: false, 
      };
    },
    methods: {
      handleChange(info) {
        // console.log(info); 
        const status = info.file.status; 
        if (status === 'uploading' && info.hasOwnProperty('event')) {
          this.loading = true;        
          this.time_spent = new Date().getTime(); 
          message.loading("Uploading " + info.file.name + " ...")
          return;
        }
        if (status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl;
            this.loading = false;
          });
          this.detectedImageUrl = "data:image/jpeg;base64," + info.file.response; 
          this.time_spent = new Date().getTime() - this.time_spent;
          message.success("Time spent " + this.time_spent / 1000 + " s"); 
        }
        if (status === 'error') {
          this.loading = false;
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      getWeights() {
        this.$axios.get(this.yolov_weights_url)
        .then(res => {
          console.log(res.data);
          res.data.forEach(weight => {
            this.options.push({ value: weight });
          });
        }).catch(err => {
          console.log(err)
        })
      }, 
      changeWeight(weight) {
        // console.log(weight);
        this.weight = weight; 
        this.yolov_detect_url = this.$axios.defaults.baseURL + "/yolov/detect?weight=" + weight;
        console.log(this.yolov_detect_url); 
        this.drawer_visible = false; 
      }, 
      changeWeightFolder() {
        this.drawer_visible = true; 
      }
    },
    mounted() {
      this.getWeights(); 
    }
  }
</script>

<style scoped>
  .detect {
    position: relative;
    overflow: hidden;
    height: 100%;
  }

  /deep/ .ant-upload .ant-upload-drag {
    min-height: 320px;
    max-height: 640px;  
  }

  /deep/ .ant-upload-drag-container > img {
    max-width: 96%;
    max-height: 608px;
  }

  /deep/ .ant-card {
    display: flex;
    padding: 16px 0; 
    min-height: 320px;
    max-height: 640px;
    justify-content: space-around;
    align-items: center;
  }

  /deep/ .ant-card-cover, .ant-card-cover > img {
    max-height: 608px;
  }

  /deep/ .ant-card-cover {
    max-width: 96%;
  }

  /deep/ .ant-card-body {
    display: none;
  }

  /deep/ .ant-page-header-heading-tags {
    margin: 0; 
  }

  /deep/ .ant-page-header-heading-sub-title {
    font-size: 13.5px;
  }

  /deep/ .ant-page-header-heading-tags {
    font-size: large;
  }

</style>